package com.ash.ptp.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息的消费者（接受者）同步等待
 *
 * @author Ashin
 */
public class JMSConsumerSync {

    /**
     * 默认连接用户名
     */
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    /**
     * 默认连接密码
     */
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    /**
     * 默认连接地址
     */
    private static final String BROKE_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) throws Exception {
        // 实例化连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(JMSConsumerSync.USERNAME,
                JMSConsumerSync.PASSWORD, JMSConsumerSync.BROKE_URL);

        // 通过连接工厂获取连接
        Connection connection = connectionFactory.createConnection();
        // 启动连接
        connection.start();
        // 创建session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 创建一个连接HelloWorld的消息队列
        Destination destination = session.createQueue("HelloWorld");
        // 创建消息消费者
        MessageConsumer messageConsumer = session.createConsumer(destination);

        while (true) {
            TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
            if (textMessage != null) {
                System.out.println("收到的消息:" + textMessage.getText());
            } else {
                break;
            }
        }

    }
}